package com.xiegang.internalcommon.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.xiegang.internalcommon.dto.TokenResult;

import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xieGang
 * @description
 * @date 2023/3/4 19:16
 **/
public class JWTUtil {

    // 盐
    private static final String SIGN = "CPFXG@*&sd-";

    private static final String JWT_PHONE = "phone";
    private static final String JWT_IDENTITY = "identity";
    private static final String JWT_TOKEN_TYPE = "tokenType";
    private static final String JWT_TOKEN_TIME = "tokenTime";

    //生成token
    public static String generatorToken(String phone, String identity, String tokenType) {
        Map<String, String> map = new HashMap<>();
        map.put(JWT_PHONE, phone);
        map.put(JWT_IDENTITY, identity);
        map.put(JWT_TOKEN_TYPE, tokenType);
        //防止每次生成的token重复
        map.put(JWT_TOKEN_TIME, LocalDateTime.now().toLocalTime().toString());

        JWTCreator.Builder builder = JWT.create();

        // 将map整合到token
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });

        //设置过期时间
//        builder.withExpiresAt(date);

        //生成 token
        String sign = builder.sign(Algorithm.HMAC256(SIGN));

        return sign;
    }

    public static TokenResult parseToken(String token) {
        TokenResult tokenResult = null;
        try{
            DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
            String phone = verify.getClaim(JWT_PHONE).asString();
            String identity = verify.getClaim(JWT_IDENTITY).asString();

            tokenResult = new TokenResult();
            tokenResult.setPhone(phone);
            tokenResult.setIdentity(identity);
        }catch (Exception e){

        }

        return tokenResult;
    }

    public static void main(String[] args) {

        String token = generatorToken("13862132236", "1","accessToken");

        System.out.println(token);
        System.out.println("解析---------------");

        TokenResult tokenResult = parseToken(token);
        System.out.println("手机号：" + tokenResult.getPhone() + "身份：" + tokenResult.getIdentity());
    }
}
